package com.jieli.nat.echo;

import java.net.InetSocketAddress;
import java.util.Vector;
import java.util.logging.Logger;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;

//L
public class EchoClientHandler7778 extends SimpleChannelInboundHandler<DatagramPacket>{
    private static Logger logger = Logger.getLogger(EchoClientHandler7778.class.getName());

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet)
            throws Exception {
        //服务器推送对方IP和PORT
        ByteBuf buf = (ByteBuf) packet.copy().content();
        byte[] req = new byte[buf.readableBytes()];
        buf.readBytes(req);
        String str = new String(req, "UTF-8");
        logger.info("接收到的信息:" + str);
        String[] list = str.split(" ");
        //如果是A 则发送
        if(list[0].equals("A")){
            String ip = list[1];
            String port = list[2];
            InetSocketAddress addressP2P = new InetSocketAddress(ip, Integer.parseInt(port));
            ctx.writeAndFlush(new DatagramPacket(
                    Unpooled.copiedBuffer("FROM7778".getBytes()), addressP2P));
            logger.info("发送打洞信息:"+addressP2P);

            for (int i = 0; i < 100; i++) {
                Thread.sleep(100);
                ctx.writeAndFlush(new DatagramPacket(
                        Unpooled.copiedBuffer("P2P info from client7778".getBytes()), addressP2P));
                logger.info("发送P2P信息:" + addressP2P);
            }
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("客户端向服务器发送自己的IP和PORT");
        InetSocketAddress server = new InetSocketAddress("139.224.19.103", 7402);
//        server = new InetSocketAddress("192.168.0.185", 7402);
        ctx.writeAndFlush(new DatagramPacket(
                Unpooled.copiedBuffer("L".getBytes()),
                server));
        super.channelActive(ctx);
    }
}